package cn.smp.server;

import cn.smp.protocol.MessageCodecSharable;
import cn.smp.protocol.ProcaotolFrameDecoder;
import cn.smp.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        final NioEventLoopGroup boss = new NioEventLoopGroup();
        final NioEventLoopGroup worker = new NioEventLoopGroup();
        final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        final MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        final LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        final ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        final GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        final GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        final GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        final GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        final GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        final QuitHandler QUIT_HANDLER = new QuitHandler();

        final ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.channel(NioServerSocketChannel.class);
        serverBootstrap.group(boss, worker);
        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                //用来判断是不是 读空闲时间过长或者写空闲时间过长
                //5s 内如果没有收到channel的数据，会触发一个 IdleState.READER_IDLE 事件
                ch.pipeline().addLast(new IdleStateHandler(5,0,0));
                //ChannelDuplexHandler 可以同时作为入站和出站的处理器
                ch.pipeline().addLast(new ChannelDuplexHandler(){
                    // 用来触发特殊事件
                    @Override
                    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                        final IdleStateEvent event = (IdleStateEvent) evt;
                        if (event.state() == IdleState.READER_IDLE) {
                            log.debug("已经 5s 没有读到数据了");
                            ctx.channel().close();
                        }
                    }
                });
                ch.pipeline().addLast(new ProcaotolFrameDecoder());
                ch.pipeline().addLast(LOGGING_HANDLER);
                ch.pipeline().addLast(MESSAGE_CODEC);
                ch.pipeline().addLast(LOGIN_HANDLER);
                ch.pipeline().addLast(CHAT_HANDLER);
                ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                ch.pipeline().addLast(GROUP_JOIN_HANDLER);
                ch.pipeline().addLast(GROUP_MEMBERS_HANDLER);
                ch.pipeline().addLast(GROUP_QUIT_HANDLER);
                ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                ch.pipeline().addLast(QUIT_HANDLER);
            }
        });
        try {
            final ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
